package com.jyw.business.obstacles.service.impl;

import com.jyw.business.obstacles.domain.vo.web.LyltConfigVO;
import com.jyw.business.obstacles.handler.UdpServerHandler;
import com.jyw.business.obstacles.service.ILyLtService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
  * 力赢力泰电话盒子服务
 *
 * @author 51047
 *
 */
@Service
@Slf4j
public class LyLtServiceImpl implements ILyLtService {

	@Resource
	private UdpServerHandler updHandler;

	@Async
	@Override
	public void init() {
		LyltConfigVO boxConfig = updHandler.getBoxConfig();
		if(boxConfig.getOpen() == 1) {
			try {
				createUdpService(boxConfig.getPort(),updHandler);
			} catch (InterruptedException e) {
				log.error("@UDP服务监听启动失败:",e);
			}
		}else {
			log.info("{}:力盈力泰盒子事件监听未打开",Thread.currentThread().getName());
		}
	}

	public static void createUdpService(Integer port, ChannelInboundHandlerAdapter handler) throws InterruptedException {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(group)
					.channel(NioDatagramChannel.class)
					.option(ChannelOption.SO_BROADCAST, true)
					// 设置读缓冲区为1M
					.option(ChannelOption.SO_RCVBUF, 1024 * 1024)
					// 设置写缓冲区为1M
					.option(ChannelOption.SO_SNDBUF, 1024 * 1024)
					.handler(new ChannelInitializer<NioDatagramChannel>() {
						@Override
						protected void initChannel(NioDatagramChannel ch) {
							ChannelPipeline pipeline = ch.pipeline();
							pipeline.addLast(new NioEventLoopGroup(),handler);
						}
					});

			ChannelFuture cf = bootstrap.bind(port).sync();
			log.info("@UDP服务在端口{}监听中......",port);
			cf.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully();
		}
	}
}
